// DrawPoint
/*
绘制文字
 */
class DrawPoint {
  constructor(arg) {
    this.viewer = arg.viewer
    this.Cesium = arg.Cesium
    this.callback = arg.callback
    this._point = null //最后一个点
    this._pointData = null //点数据用于构造点
    this._entities = [] //脏数据
    this.popover = null //文本框元素
    this.textStyle = {} //文字的颜色
  }

  //返回最后活动点
  get point() {
    return this._point
  }

  //加载点
  loadPoint(data) {
    return this.createText(data)
  }

  //返回点数据用于加载点
  getData() {
    return this._pointData
  }

  //开始绘制
  startCreate(option) {
    var $this = this
    this.textStyle = option
    this.viewer.cesiumViewer.scene.globe.depthTestAgainstTerrain = false
    this.handler = new this.Cesium.ScreenSpaceEventHandler(this.viewer.cesiumViewer.scene.canvas)
    this.handler.setInputAction(function (evt) { //单机开始绘制
      var cartesian = $this.getCatesian3FromPX(evt.position)
      if (!cartesian) return
      $this.popover = document.querySelector('.popover_span')
      const winpos = $this.viewer.cesiumViewer.scene.cartesianToCanvasCoordinates(cartesian)
      $this.popover.style.display = "block"
      $this.popover.style.left = winpos.x - $this.popover.offsetWidth / 2 + 'px'
      $this.popover.style.top = winpos.y - $this.popover.offsetHeight / 2 + 'px'
      
      $this._pointData = cartesian
    }, $this.Cesium.ScreenSpaceEventType.LEFT_CLICK)
  }

  //创建点
  createText(text) {
    var $this = this
    var label = this.viewer.dataSourceDisplay._defaultDataSource.entities.add({
      position: $this._pointData,
      label: {
        text,
        font: "20px sans-serif",
        fillColor: $this.Cesium.Color.fromCssColorString($this.textStyle.color),
        showBackgroun: true,
        heightReference: $this.Cesium.HeightReference.CLAMP_TO_GROUND,
        backgroundColor: $this.Cesium.Color.fromCssColorString("rgab(0,0,0,0.5)")
      }
    })
    $this.popover.style.display = "none"
    $this._entities.push(label) //加载脏数据
    return label
  }

  //销毁鼠标事件
  destroy() {
    if (this.handler) {
      this.handler.destroy()
      this.handler = null
    }
  }

  //清空实体对象
  clear() {
    for (var i = 0; i < this._entities.length; i++) {
      this.viewer.dataSourceDisplay._defaultDataSource.entities.remove(this._entities[i])
    }
    this._entities = []
    this._point = null
  }

  getCatesian3FromPX(px) {
    var cartesian
    var ray = this.viewer.cesiumViewer.camera.getPickRay(px)
    if (!ray) return null
    cartesian = this.viewer.cesiumViewer.scene.globe.pick(ray, this.viewer.cesiumViewer.scene)
    if (!cartesian) {
      cartesian = this.viewer.cesiumViewer.camera.pickEllipsoid(px, this.viewer.cesiumViewer.scene.globe.ellipsoid)
    }
    return cartesian
  }
}

export default DrawPoint
